from datetime import datetime
from datetime import datetime as dt
from datetime import timedelta
import re
import logging

logger = logging.getLogger("scraper")

# 将Facebook时间字符串转换为时间戳
def convert_facebook_time_to_timestamp(time_str):
  """
  将Facebook时间字符串转换为Unix时间戳
  支持以下格式:
  - 相对时间: 如 "18分钟"、"2小时"、"1天"、"1周"
  - 绝对时间: 如 "3月26日15:03"、"2023年3月26日15:03"
  
  返回: Unix时间戳(秒)
  """
  now = datetime.now()
  
  # 相对时间模式匹配
  relative_patterns = [
    (r'(\d+)\s*分钟', lambda m: now - timedelta(minutes=int(m.group(1)))),
    (r'(\d+)\s*小时', lambda m: now - timedelta(hours=int(m.group(1)))),
    (r'(\d+)\s*天', lambda m: now - timedelta(days=int(m.group(1)))),
    (r'(\d+)\s*周', lambda m: now - timedelta(weeks=int(m.group(1)))),
    (r'昨天', lambda m: now - timedelta(days=1)),
    (r'前天', lambda m: now - timedelta(days=2)),
  ]
  
  # 绝对时间模式匹配
  absolute_patterns = [
    # 3月26日15:03
    (r'(\d+)月(\d+)日(\d+):(\d+)', 
     lambda m: datetime(now.year, int(m.group(1)), int(m.group(2)), int(m.group(3)), int(m.group(4)))),
    # 2023年3月26日15:03
    (r'(\d+)年(\d+)月(\d+)日(\d+):(\d+)', 
     lambda m: datetime(int(m.group(1)), int(m.group(2)), int(m.group(3)), int(m.group(4)), int(m.group(5))))
  ]
  
  # 尝试匹配相对时间
  for pattern, time_func in relative_patterns:
    match = re.search(pattern, time_str)
    if match:
      dt = time_func(match)
      return int(dt.timestamp())
  
  # 尝试匹配绝对时间
  for pattern, time_func in absolute_patterns:
    match = re.search(pattern, time_str)
    if match:
      dt = time_func(match)
      # 如果计算出的时间在未来，可能是去年的日期
      if dt > now:
        dt = dt.replace(year=dt.year - 1)
      return int(dt.timestamp())
  
  # 如果无法解析，记录警告并返回当前时间戳
  logger.warning(f"无法解析时间字符串: {time_str}")
  return int(now.timestamp())
